package com.irdstudio.efp.console.api.rest;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import com.irdstudio.basic.framework.core.constant.PubConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.irdstudio.efp.console.service.facade.RiskClassfyCfgService;
import com.irdstudio.efp.console.service.vo.RiskClassfyCfgVO;
import com.irdstudio.efp.console.service.vo.RiskClassfyListVO;
import com.irdstudio.efp.e4a.service.facade.SRoleDataRuleService;
import com.irdstudio.basic.framework.core.constant.ApplicationConstance;
import com.irdstudio.basic.framework.core.constant.DataRuleType;
import com.irdstudio.basic.framework.core.constant.ResponseData;
import com.irdstudio.basic.framework.core.util.TimeUtil;
import com.irdstudio.basic.framework.web.controller.AbstractController;
import com.irdstudio.efp.limit.common.util.ExcelExportUtil;

@RestController
@RequestMapping("/api")
public class RiskClassfyCfgController extends AbstractController  {
	
	@Autowired
	@Qualifier("riskClassfyCfgService")
	private RiskClassfyCfgService riskClassfyCfgService;
	@Autowired
	@Qualifier("sRoleDataRuleService")
	private SRoleDataRuleService sRoleDataRuleService;
	
	/**
	 * 列表数据查询
	 * @param page
	 * @param size
	 * @return
	 */
	@RequestMapping(value="/risk/classfy/cfgs", method=RequestMethod.POST)
	public @ResponseBody ResponseData<List<RiskClassfyCfgVO>> queryRiskClassfyCfgAll(
			@RequestBody RiskClassfyCfgVO vo) {		
		List<RiskClassfyCfgVO> outputVo = null;
		Map<String,String> dataRuleTypeMap = sRoleDataRuleService.getDataRuleType(httpRequest.getRequestURI(), getUserRoles());
		vo.setPrdCodebyBaseInfo(dataRuleTypeMap == null ? null:dataRuleTypeMap.get(PubConstant.PRD_CODE));
		DataRuleType dataRuleType = DataRuleType.getDataRuleType(dataRuleTypeMap == null ? null:dataRuleTypeMap.get(PubConstant.PERMIS_TYPE));
		setUserInfoToVO(vo);

		// 根据权限方案调用不同的方案进行数据查询
		switch (dataRuleType) {
		case Owner:
			outputVo = riskClassfyCfgService.queryAllOwner(vo);
			break;
		case CurrOrg:
			outputVo = riskClassfyCfgService.queryAllCurrOrg(vo);
			break;
		case CurrDownOrg:
			outputVo = riskClassfyCfgService.queryAllCurrDownOrg(vo);
			break;
		default:
			outputVo = riskClassfyCfgService.queryAllOwner(vo);
			break;
		}
		return getResponseData(outputVo);
	}
	
	/**
	 * 根据主键查询详情
	 * @return
	 */
	@RequestMapping(value="/risk/classfy/cfg/{riskCfgNo}", method=RequestMethod.GET)
	public @ResponseBody ResponseData<RiskClassfyCfgVO> queryByPk(@PathVariable("riskCfgNo") String riskCfgNo) {		
		RiskClassfyCfgVO inVo = new RiskClassfyCfgVO();
		inVo.setRiskCfgNo(riskCfgNo);
		RiskClassfyCfgVO outputVo = riskClassfyCfgService.queryByPk(inVo);
		return getResponseData(outputVo);
	}
	
	/**
	 * 根据主键删除信息
	 * @param riskClassfyCfg
	 * @return
	 */
	@RequestMapping(value="/risk/classfy/cfg", method=RequestMethod.DELETE)
	public @ResponseBody ResponseData<Integer> deleteByPk(@RequestBody RiskClassfyCfgVO inRiskClassfyCfgVo) {		
		int outputVo = riskClassfyCfgService.deleteByPk(inRiskClassfyCfgVo);
		if ( outputVo == -2 ) {
			String message = "只能删除待生效状态的风险分类配置!";
			return setMessage(outputVo, message);
		}else
			return getResponseData(outputVo);
	}
	
	/**
	 * 根据主键更新信息
	 * @param inRiskClassfyCfgVo
	 * @return
	 */
	@RequestMapping(value="/risk/classfy/cfg", method=RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> updateByPk(@RequestBody RiskClassfyCfgVO inRiskClassfyCfgVo) {		
		setUserInfoToVO(inRiskClassfyCfgVo);
		int outputVo = riskClassfyCfgService.updateByPk(inRiskClassfyCfgVo);
		return getResponseData(outputVo);
	}
	/**
	 * 提交将 状态变为生效
	 * @param inRiskClassfyCfgVo
	 * @return
	 */
	@RequestMapping(value="/risk/classfy/cfg/submit", method=RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> updateSubmitByPk(@RequestBody RiskClassfyCfgVO inRiskClassfyCfgVo) {		
		setUserInfoToVO(inRiskClassfyCfgVo);
		int outputVo = riskClassfyCfgService.updateSubmitByPk(inRiskClassfyCfgVo);
		if (outputVo < 0) {
			String message;
			switch (outputVo) {
			case -3:
				message = "风险分类配置下不存在风险分类配置清单信息,不能生效!";
				break;
			case -4:
				message = "已存在已生效的风险分类配置，则不允许新增风险分类配置!";
				break;
			default:
				message = "处理失败!";
				break;
			}
			return setMessage(outputVo, message);
		}else
			return getResponseData(outputVo);
	}
	/**
	 * 失效将 状态变为失效
	 * @param inRiskClassfyCfgVo
	 * @return
	 */
	@RequestMapping(value="/risk/classfy/cfg/disabled", method=RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> updateDisabledByPk(@RequestBody RiskClassfyCfgVO inRiskClassfyCfgVo) {		
		setUserInfoToVO(inRiskClassfyCfgVo);
		int outputVo = riskClassfyCfgService.updateDisabledByPk(inRiskClassfyCfgVo);
		return getResponseData(outputVo);
	}
	
	/**
	 * 新增数据
	 * @param inRiskClassfyCfgVo
	 * @return
	 */
	@RequestMapping(value="/risk/classfy/cfg", method=RequestMethod.POST)
	public @ResponseBody ResponseData<RiskClassfyCfgVO> insertRiskClassfyCfg(@RequestBody RiskClassfyCfgVO inRiskClassfyCfgVo) {
		setUserInfoToVO(inRiskClassfyCfgVo);
		RiskClassfyCfgVO outputVo = riskClassfyCfgService.insertRiskInfoBack(inRiskClassfyCfgVo);
		if (outputVo.getTotal() < 0) {
			String message;
			if(outputVo.getTotal() == -4) {
				message = "已存在已生效的风险分类配置，则不允许新增风险分类配置!";
			}else {
				message = "处理失败!";
			}
			ResponseData<RiskClassfyCfgVO> responseData = new ResponseData<RiskClassfyCfgVO>();
			responseData.setRows(outputVo);
			responseData.setMessage(message);
			responseData.setCode(ApplicationConstance.FAILURE);
			responseData.setSuccess(false);
			return responseData;
		}
			return getResponseData(outputVo);
	}
	
	/**
	 * 查询风险分类配置下的 所有 配置清单
	 * @param page
	 * @param size
	 * @return
	 */
	@RequestMapping(value="/risk/classfy/lists", method=RequestMethod.POST)
	public @ResponseBody ResponseData<List<RiskClassfyListVO>> queryRiskClassfyListAll(
			@RequestBody RiskClassfyListVO vo) {		
		List<RiskClassfyListVO> outputVo = riskClassfyCfgService.queryListAll(vo);
		return getResponseData(outputVo);
	}
	
	/**
	 * 新增 风险分类配置清单数据
	 * @param inRiskClassfyListVo
	 * @return
	 */
	@RequestMapping(value="/risk/classfy/list", method=RequestMethod.POST)
	public @ResponseBody ResponseData<Integer> insertRiskClassfyList(@RequestBody RiskClassfyListVO inRiskClassfyListVo) {
		setUserInfoToVO(inRiskClassfyListVo);
		int outputVo = riskClassfyCfgService.insertRiskClassfyList(inRiskClassfyListVo);
		if ( outputVo < 0) {
			String message = "处理失败";
			if (outputVo == -2)
				message = "已存在同一逾期最小天数、逾期最大天数、担保方式、是否涉农、客户评级各维度相组合的一条配置信息!";
			else if (outputVo == -3)
				message = "当担保方式、是否涉农、客户评级相同时,输入的最小逾期数和最大逾期数已存在交叉!";
			return setMessage(outputVo, message);
		}else
			return getResponseData(outputVo);
	}
	
	/**
	 * 根据主键更新风险分类配置清单信息
	 * @param inRiskClassfyListVo
	 * @return
	 */
	@RequestMapping(value="/risk/classfy/list", method=RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> updateRiskClassfyListByPk(@RequestBody RiskClassfyListVO inRiskClassfyListVo) {		
		setUserInfoToVO(inRiskClassfyListVo);
		int outputVo = riskClassfyCfgService.updateRiskClassfyListByPk(inRiskClassfyListVo);
		if ( outputVo < 0) {
			String message = "处理失败";
			if (outputVo == -2)
				message = "已存在同一逾期最小天数、逾期最大天数、担保方式、是否涉农、客户评级各维度相组合的一条配置信息!";
			else if (outputVo == -3)
				message = "当担保方式、是否涉农、客户评级相同时,输入的最小逾期数和最大逾期数已存在交叉!";
			
			return setMessage(outputVo, message);
		}else
			return getResponseData(outputVo);
	}
	
	/**
	 * 根据主键删除信息
	 * @param riskClassfyList
	 * @return
	 */
	@RequestMapping(value="/risk/classfy/list", method=RequestMethod.DELETE)
	public @ResponseBody ResponseData<Integer> deleteByPk(@RequestBody RiskClassfyListVO inRiskClassfyListVo) {		
		int outputVo = riskClassfyCfgService.deleteRiskClassfyListByPk(inRiskClassfyListVo);
		return getResponseData(outputVo);
	}
	
	@RequestMapping(value="/risk/classfy/list/download")
	public void downloadRiskClassfyList(@RequestParam("riskCfgNo")String riskCfgNo,
			@RequestParam("fileName")String fileName,
			HttpServletResponse res) {	
		RiskClassfyListVO inRiskClassfyListVo = new RiskClassfyListVO();
		inRiskClassfyListVo.setRiskCfgNo(riskCfgNo);
		
		List<RiskClassfyListVO> lists = riskClassfyCfgService.queryListAllByCfgNo(inRiskClassfyListVo);
		if ( null == lists || lists.size() == 0)
			return ;
		try {
			this.setResponseHeader(res, fileName);
			OutputStream out = res.getOutputStream();
			byte[] bytes = ExcelExportUtil.exportToBytes(lists);
			out.write(bytes);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ;
	}
	
	 //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            fileName = fileName + TimeUtil.getCurrentDateTime() + ".xls";
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    private ResponseData<Integer> setMessage(Integer outputVo, String message) {
    	ResponseData<Integer> responseData = new ResponseData<Integer>();
		responseData.setRows(outputVo);
		responseData.setMessage(message);
		responseData.setCode(ApplicationConstance.FAILURE);
		responseData.setSuccess(false);
		return responseData;
    }
    
}
